package com.one.blocks.mvc.valid.validator;

import com.one.blocks.mvc.valid.constraints.Unique;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationContext;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

/**
 * @author <a href="mailto:idler41@163.com">linfuxin</a> created by 2022-12-11 16:10:44
 */
@Slf4j
public abstract class AbstractUniqueValidator<K> implements ConstraintValidator<Unique, K> {

    protected final ApplicationContext applicationContext;
    protected UniqueManager<K> validateManager;

    public AbstractUniqueValidator(ApplicationContext applicationContext) {
        this.applicationContext = applicationContext;
    }

    @SuppressWarnings("unchecked")
    @Override
    public void initialize(Unique constraintAnnotation) {
        ConstraintValidator.super.initialize(constraintAnnotation);
        Class<? extends UniqueManager<K>> validManagerClass =
                (Class<? extends UniqueManager<K>>) constraintAnnotation.manager();
        validateManager = applicationContext.getBean(validManagerClass);
    }

    @Override
    public boolean isValid(K k, ConstraintValidatorContext context) {
        return validateManager.isUnique(k, context);
    }
}
